package com.sss.springcloud.controller;

import com.sss.springcloud.common.Result;
import com.sss.springcloud.entities.Payment;
import com.sss.springcloud.ribbon.MyLoadBalance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * @author sss
 * @date 2020-03-05 19:34
 **/
@RestController
public class OrderController {
   // private static  final String PAYMENT_URL="http://localhost:8081";
    private static  final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE";
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private MyLoadBalance myLoadBalance;

    @GetMapping("/consumer/payment/create")
    public Result<Payment> create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,Result.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public Result<Payment> getPayment(@PathVariable Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,Result.class);
    }

    @GetMapping("/consumer/payment/get/ribbon")
    public Result<Payment> getRibbon(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        ServiceInstance serviceInstance = myLoadBalance.getServiceInstance(instances);
        if (serviceInstance==null) {
            return null;
        }
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/payment/get/ribbon",Result.class);
    }

    @GetMapping("/consumer/payment/get/zipkin")
    public Result getZipkin(){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/zipkin",Result.class);
    }

}
